package com.example.moonshine.redchange.Activity;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.widget.Switch;
import android.widget.Toast;

import com.example.moonshine.redchange.Fragment.FirstFragment;
import com.example.moonshine.redchange.Util.DataUrl;
import com.example.moonshine.redchange.Util.SaveParmasUtrl;

import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;



public class Servicetcp extends Service {
    EchoWebSocketListener listener;

    //判断处于那个界面
    String index = "fragment";
    private LocalReceiver mReceiver;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onCreate() {
        super.onCreate();

//        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
//                .readTimeout(30000, TimeUnit.SECONDS)//设置读取超时时间
//                .writeTimeout(30000, TimeUnit.SECONDS)//设置写的超时时间
//                .connectTimeout(30000, TimeUnit.SECONDS)//设置连接超时时间
//                .build();
        listener = new EchoWebSocketListener();
        Request request = new Request.Builder()
                .url(DataUrl.websocketUrl)
                .build();
        OkHttpClient client = new OkHttpClient();
        client.newWebSocket(request, listener);
        client.dispatcher().executorService().shutdown();

    }

    public final class EchoWebSocketListener extends WebSocketListener {
        SaveParmasUtrl saveParmasUtrl = new SaveParmasUtrl();
        private Handler mDelivery;
        WebListener http;
        WebSocket webSocket;

        public void setHttp(WebListener listener) {
            this.http = listener;
        }

        private EchoWebSocketListener() {
        }

        private EchoWebSocketListener urlservice;

        public WebSocketListener getinstace() {
            if (urlservice == null) {
                synchronized (EchoWebSocketListener.class) {
                    if (urlservice == null) {
                        urlservice = new EchoWebSocketListener();
                    }
                }
            }
            return urlservice;
        }

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            this.webSocket = webSocket;
            mDelivery = new Handler(Looper.getMainLooper());
            Log.i("tag","连接成功");

        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onMessage(WebSocket webSocket, final String text) {
            System.out.println("onMessage: " + text);

            if (text.equals("000"))
            {
                Log.i("EchoWebSocketListener", "发给fragment   000");
                Intent intent = new Intent();
                intent.putExtra("text", text);
                intent.setAction("fragment_home");
                BroadCastManager.getInstance().sendBroadCast(Servicetcp.this, intent);
            }
            else if (text.equals("finishOn") || text.equals("finishOff")){

                 saveParmasUtrl.saveInfo(Servicetcp.this,"text",text,"file");
                Log.i("EchoWebSocketListener", "发给fragmentList");
                Intent intent = new Intent();
                intent.putExtra("text", text);
                intent.setAction("fragmentList_home");
                BroadCastManager.getInstance().sendBroadCast(Servicetcp.this, intent);

            }else if (text.equals("bottomOn") || text.equals("bottomOff")){

                saveParmasUtrl.saveInfo(Servicetcp.this,"text1",text,"file");
                Log.i("EchoWebSocketListener", "发给fragmentList");
                Intent intent = new Intent();
                intent.putExtra("text", text);
                intent.setAction("fragmentList_home");
                BroadCastManager.getInstance().sendBroadCast(Servicetcp.this, intent);
            }else {
                //修改首页
                switch (index){
                    case "fragment":  send("fragment_home",text);break;
                    case "fragmentList":  send("fragmentList_home",text);break;
                    case "change_home":  send("change_home",text);break;
                    default:break;
                }
            }

        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
//            System.out.println("onMessage byteString: " + bytes);
            http.output("onMessage byteString: " + bytes);
        }

        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            webSocket.close(1000, null);
//            System.out.println("onClosing: " + code + "/" + reason);
            http.output("onClosing: " + code + "/" + reason);
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            http.output("onClosed: " + code + "/" + reason);
//            System.out.println("onClosed: " + code + "/" + reason);
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {

            try {
                http.output("onFailure: " + t.getMessage());


            } catch (Exception e) {
                e.printStackTrace();

                new Thread(){
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(20000);
                            Log.i("Service","重连");
                            //重连
                            listener = new EchoWebSocketListener();
                            Request request = new Request.Builder()
                                    .url(DataUrl.websocketUrl)
                                    .build();
                            OkHttpClient client = new OkHttpClient();
                            client.newWebSocket(request, listener);
                            client.dispatcher().executorService().shutdown();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        }


        /**
         * @param s
         * @return
         */
        public boolean sendMessage(String s) {
            return webSocket.send(s);
        }

        public boolean closeMessage() {
            return webSocket.close(1000, "");
        }
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        // A client is binding to the service with bindService(),
        // after onUnbind() has already been called
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // The service is no longer used and is being destroyed
    }

    public void send(String msg,String text){
        Intent intent = new Intent();
        intent.putExtra("text", text);
        intent.setAction(msg);
        BroadCastManager.getInstance().sendBroadCast(Servicetcp.this, intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction("service");
            mReceiver = new LocalReceiver();
            BroadCastManager.getInstance().registerReceiver(this, mReceiver, filter);//注册广播接收者
        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.onStartCommand(intent, flags, startId);
    }


    class LocalReceiver extends BroadcastReceiver {

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onReceive(Context context, Intent intent) {
            //收到广播后的处理
            index = intent.getStringExtra("status");

            Log.i("tag", "Service传参的数字为:" + index);
        }
    }
}
